package com.zj.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.List;

/**
 * 工作节点  服务器id分配器
 */
@Component
public class WorkerIdAssigner {
    //通过nacos客户端来获取workerId
    @Autowired
    private DiscoveryClient discoveryClient;
    @Value("${spring.application.name}")  //从配置文件获取服务名，这样 discoveryClient可以根据服务名取实例列表
    private String serviceName;

    public Long getWorkerId(){
        //TODO:以后从nacos服务注册中心获取workerId
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        try {

            String currentIp = InetAddress.getLocalHost().getHostAddress();
            long index=0;
            for (int i = 0; i < instances.size(); i++) {
                if(  instances.get(i).getHost().equals(currentIp)  ){
                    index=i;

                }
            }
            return index;
        }catch (Exception e){
            throw new RuntimeException("获取workerId失败"+e);
        }
    }
}
